import { Form, Input, Button, message } from 'antd';
import React, { useState } from 'react';
import { connect, Dispatch } from 'umi';
import { StateType } from '@/models/login';
import { checkMobile, LoginParamsType, sendMobileSmsVerificationCode } from '@/services/login';
import { ConnectState } from '@/models/connect';

import styles from './index.less';

interface LoginProps {
  dispatch: Dispatch;
  userLogin?: StateType;
  submitting?: boolean;
}

const Login: React.FC<LoginProps> = props => {
  const { submitting } = props;
  const [form] = Form.useForm();
  const [num, setnum] = useState<number>(0);
  const [isdisable, setdisable] = useState<boolean>(false);

  /**
   * 登录
   * @param values
   */
  const handleSubmit = (values: LoginParamsType): void => {
    const { dispatch } = props;
    dispatch({
      type: 'login/login',
      payload: { ...values },
    });
  };

  /**
   * 验证码自执行
   */
  const setNum = (): void => {
    let conent: number = 60;
    let time = setInterval(() => {
      conent--;
      setnum(() => {
        if (conent == 0) {
          clearInterval(time);
          setdisable(false);
          return 0;
        }
        return conent;
      });
    }, 1000);
  };

  /**
   * 点击验证码
   */
  const numCurrent = (): void => {
    setdisable(true);
    form
      .validateFields(['mobile'])
      .then((values: LoginParamsType) => {
        checkMobile({ mobile: values?.mobile }).then(res => {
          if (res?.responseCode == 200 && res?.data) {
            sendMobileSmsVerificationCode({ mobile: values?.mobile }).then(resp => {
              if (resp?.responseCode == 200) {
                message.success({
                  key: 'IS',
                  content: '短信发送成功！',
                });
                setNum();
              } else {
                setdisable(false);
                message.error('短信发送失败！');
              }
            });
          } else {
            form.setFields([
              {
                name: 'mobile',
                value: values?.mobile,
                errors: ['用户不存在'],
              },
            ]);
            setdisable(false);
          }
        });
      })
      .catch((err: any) => {
        setdisable(false);
      });
  };
  return (
    <div className={styles.main}>
      <Form name="basic" form={form} onFinish={handleSubmit}>
        <Form.Item label="" name="mobile" rules={[{ required: true, message: '手机号码不能为空！' }]}>
          <Input size="large" placeholder="请输入您的手机号码" />
        </Form.Item>

        <div className={styles.captcha}>
          <Form.Item label="" name="smsVerificationCode" rules={[{ required: true, message: '验证码不能为空！' }]}>
            <Input size="large" placeholder="" />
          </Form.Item>
          <Button className={styles.captchaBtn} disabled={Boolean(num) || isdisable} size="large" onClick={numCurrent}>
            {num ? `${num}秒后重试` : '获取验证码'}
          </Button>
        </div>

        <Button loading={submitting} className={styles.btn} size="large" htmlType="submit">
          登录
        </Button>
      </Form>
    </div>
  );
};

export default connect(({ login, loading }: ConnectState) => ({
  userLogin: login,
  submitting: loading.effects['login/login'],
}))(Login);
